﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tasker.Composition;
using Tasker.Infrastructure.Entities;
using Tasker.Infrastructure.Repositories;
using Tasker.Infrastructure.Repositories.Base;
using Tasker.Repositories.Entities;

namespace Tasker.Repositories
{
    class UserPhonesRepositoryEF: IUserPhonesRepository
    {
        private EntitiesContext _context = Resolver.Resolve<EntitiesContext>();
        private IContextManager _manager = Resolver.Resolve<IContextManager>();

        public IUserPhone SelectById(int id)
        {
            return _context.UserPhones.SingleOrDefault(up => up.Id == id);
        }

        public IEnumerable<IUserPhone> SelectAll()
        {
            return _context.UserPhones.ToList();
        }

        public IEnumerable<IUserPhone> SelectByUserId(int userId)
        {
            return _context.UserPhones.Where(up => up.UserId == userId);
        }

        public void DeleteAll(int userId)
        {
            IEnumerable<UserPhone> userPhones = _context.UserPhones.Where(up => up.UserId == userId);
            foreach (UserPhone userPhone in userPhones)
            {
                _context.UserPhones.DeleteObject(userPhone);
            }
        }

        public void Update(IUserPhone entity)
        {
            UserPhone res = _context.UserPhones.SingleOrDefault(up => up.Id == entity.Id);

            res.Phone = entity.Phone;
            res.UserId = entity.UserId;

            _manager.Save();
        }

        public IUserPhone Create()
        {
            return new UserPhone();
        }

        public void Delete(IUserPhone entity)
        {
            UserPhone userPhone = _context.UserPhones.SingleOrDefault(up => up.Id == entity.Id);
            _context.UserPhones.DeleteObject(userPhone);
        }

        public IUserPhone Insert(IUserPhone entity)
        {
            UserPhone res = entity as UserPhone;
            _context.UserPhones.AddObject(res);
            _manager.Save();
            return res;
        }
    }
}
